#!/bin/bash
# perform sanity checks, make packages
VER=`grep AC_INIT configure.ac | sed 's/.*\[\([0-9]*\.[0-9]*\.[0-9]*\)\].*/\1/'`
echo making pbc-$VER
GREPVER=${VER//\./\\.}
if [[ $1 == "test" ]]; then
    echo test run
    TESTRUN=1
fi
echo cg-diff: ideally should do nothing...
cg-diff
cg-log > ChangeLog
cat ChangeLog | head -20 | grep pbc-$GREPVER > /dev/null || {
    echo cg-log does not mention release 
    if [[ $TESTRUN ]]; then
	echo test run: continuing anyway...
    else
	exit 1
    fi
}
TMPDIR=`mktemp -d` || {
    echo Error creating temp directory
    exit 1
}
PBCDIR=$TMPDIR/pbc-$VER
echo Running setup...
cg-export $PBCDIR
HERE=`pwd`
cp ChangeLog $PBCDIR
cd $PBCDIR
grep $GREPVER NEWS > /dev/null || {
    echo NEWS does not mention release 
    if [[ $TESTRUN ]]; then
	echo test run: continuing anyway...
    else
	cd $HERE
	rm -rf $TMPDIR
	exit 1
    fi
}
grep $GREPVER doc/manual.xml > /dev/null || {
    echo Error: doc/manual.xml version number mismatch
    if [[ $TESTRUN ]]; then
	echo test run: continuing anyway...
    else
	cd $HERE
	rm -rf $TMPDIR
	exit 1
    fi
}
./setup || {
    echo ./setup error
    rm -rf $TMPDIR
    exit 1
}
cd $TMPDIR
echo Creating tarball...
rm -rf $PBCDIR/autom4te.cache
if [[ $TESTRUN ]]; then
    echo test run: not building tarball...
else
    tar cvfz $HERE/pbc-$VER.tar.gz pbc-$VER
fi
cd $PBCDIR
./configure || {
    echo ./configure error
    rm -rf $TMPDIR
    exit 1
}
#make dist || {
    #echo make dist error
    #rm -rf $TMPDIR
    #exit 1
#}
#mv $TMPDIR/pbc-$VER.tar.gz $HERE || {
    #echo Failed: mv $PBCDIR/pbc-$VER.tar.gz
    #rm -rf $TMPDIR
    #exit 1
#}
echo Testing make...
make || {
    echo make error
    rm -rf $TMPDIR
    exit 1
}
make clean
echo cmake with cross compile
cmake -Dcrossmingw:BOOL=1 . || {
    echo cmake mingw cross compile error
    rm -rf $TMPDIR
    exit 1
}
make || {
    echo mingw cross compile error
    rm -rf $TMPDIR
    exit 1
}
if [[ $TESTRUN ]]; then
    echo test run: not building zip...
else
    mkdir pbc-$VER
    mv pbc/*.exe benchmark/*.exe param/* pbc-$VER
    zip -r $HERE/pbc-$VER-win32-bin.zip pbc-$VER
fi
rm -rf $TMPDIR
